#include <iostream>
#include <memory>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>


int main() {
    //编写一个scoket 客户端连接我本地的8080端口，并发送一个字符串 "Hello, Server!"，然后接收服务器的响应并打印出来。
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        std::cerr << "Socket creation failed!" << std::endl;
        return -1;
    }
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Connection to server failed!" << std::endl;
        close(sockfd);
        return -1;
    }
    const char* message = "Hello, Server!";
    send(sockfd, message, strlen(message), 0);
    char buffer[1024] = {0};
    ssize_t bytes_received = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if (bytes_received < 0) {
        std::cerr << "Receive failed!" << std::endl;
        close(sockfd);
        return -1;
    }
    buffer[bytes_received] = '\0'; // Null-terminate the received string
    std::cout << "Received from server: " << buffer << std::endl;
    close(sockfd);

    return 0;
}

